import java.util.Arrays;

public class GraphByMatrix {
    public char[] arrayV;//存储顶点
    public int[][] matrix;//邻接矩阵
    public boolean isDirect; //是否为有向图

    /*
    提供构造方法，size 顶点的个数
    isDirect : 是否为有向图
     */
    public GraphByMatrix(int size, boolean isDirect) {
        this.arrayV = new char[size];
        matrix = new int[size][size];
        for (int i = 0; i < matrix.length; i++) {
            Arrays.fill(matrix[i],Integer.MAX_VALUE);
        }
        this.isDirect = isDirect;
    }

    //初始化顶点数组
    public void initArrayV(char[] arr) {
        for (int i = 0; i < arr.length; i++) {
            this.arrayV[i] = arr[i];
        }
    }

    //添加边，同时给两个边加上权重
    public void addEdge(char v1, char v2, int weight) {
        //获取下标
        int index1 = getIndexOfValue(v1);
        int index2 = getIndexOfValue(v2);

        matrix[index1][index2] = weight;

        //如果是无向图,对角地方也要添加
        if(!isDirect) {
            matrix[index2][index1] = weight;
        }
    }

    //获取下标
    public int getIndexOfValue(char ch) {
        for (int i = 0; i < arrayV.length; i++) {
            if(arrayV[i] == ch) {
                return i;
            }
        }
        return -1;
    }

    //获得顶点的度
    public int getDegreeOfValue(char ch) {
        int count = 0;
        int index = getIndexOfValue(ch);
        for (int i = 0; i < arrayV.length; i++) {
            if(matrix[index][i] != Integer.MAX_VALUE) {
                count++;
            }
        }

        //如果是有向图,还要计算入度
        if(isDirect) {
            for (int i = 0; i < arrayV.length; i++) {
                for (int j = 0; j < arrayV.length; j++) {
                    if(i != index && j == index && matrix[i][j] != Integer.MAX_VALUE) {
                        count++;
                    }
                }
            }
        }
        return count;
    }

    //打印图
    public void printGraph() {
        int n = arrayV.length;
        for (int i = 0; i < n; i++) {
            System.out.print(arrayV[i] + " ");
        }
        System.out.println();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if(matrix[i][j] == Integer.MAX_VALUE) {
                    System.out.print("∞ ");
                } else {
                    System.out.print(matrix[i][j] + " ");
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        GraphByMatrix graph = new GraphByMatrix(4,false);
        char[] arr = {'A','B','C','D'};
        graph.initArrayV(arr);
        graph.addEdge('A','B',10);
        graph.addEdge('A','D',20);
        graph.addEdge('B','C',10);
        graph.addEdge('D','C',14);

        graph.printGraph();

        System.out.println(graph.getDegreeOfValue('C'));
    }
}
